<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="主键" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="主键"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="店铺名称" prop="storeName">
          <el-input
            v-model="queryParams.storeName"
            placeholder="店铺名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="报告日期" prop="reportDate">
          <el-date-picker
            class="!w-[240px]"
            v-model="queryParams.reportDate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['system:supply-chain-report:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:supply-chain-report:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="主键"
          prop="id"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="storeName"
          label="店铺名称"
          prop="storeName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="reportDate"
          label="报告日期"
          prop="reportDate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="spotQuantity"
          label="现货数量（箱）"
          prop="spotQuantity"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="inTransitQuantity"
          label="在途数量（箱）"
          prop="inTransitQuantity"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="totalQuantity"
          label="合计数量（箱）"
          prop="totalQuantity"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="spotAmount"
          label="现货金额（万元）"
          prop="spotAmount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="inTransitAmount"
          label="在途金额（万元）"
          prop="inTransitAmount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="totalAmount"
          label="合计金额（万元）"
          prop="totalAmount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="spotTurnoverDays"
          label="现货周转天数"
          prop="spotTurnoverDays"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="withInTransitTurnoverDays"
          label="含在途周转天数"
          prop="withInTransitTurnoverDays"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="nrTarget"
          label="本月NR目标（万元）"
          prop="nrTarget"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="orderedAmount"
          label="已下单金额（万元）"
          prop="orderedAmount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="achievementRate"
          label="达成率（%）"
          prop="achievementRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="pvSpotRate"
          label="PV现货率（%）"
          prop="pvSpotRate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:supply-chain-report:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:supply-chain-report:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 供应链日报表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="店铺名称" prop="storeName">
          <el-input
            v-model="formData.storeName"
            placeholder="店铺名称"
          />
        </el-form-item>

        <el-form-item label="报告日期" prop="reportDate">
          <el-date-picker
            class="!w-[240px]"
            v-model="formData.reportDate"
            type="date"
            placeholder="报告日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="现货数量（箱）" prop="spotQuantity">
          <el-input
            v-model="formData.spotQuantity"
            placeholder="现货数量（箱）"
          />
        </el-form-item>

        <el-form-item label="在途数量（箱）" prop="inTransitQuantity">
          <el-input
            v-model="formData.inTransitQuantity"
            placeholder="在途数量（箱）"
          />
        </el-form-item>

        <el-form-item label="合计数量（箱）" prop="totalQuantity">
          <el-input
            v-model="formData.totalQuantity"
            placeholder="合计数量（箱）"
          />
        </el-form-item>

        <el-form-item label="现货金额（万元）" prop="spotAmount">
          <el-input
            v-model="formData.spotAmount"
            placeholder="现货金额（万元）"
          />
        </el-form-item>

        <el-form-item label="在途金额（万元）" prop="inTransitAmount">
          <el-input
            v-model="formData.inTransitAmount"
            placeholder="在途金额（万元）"
          />
        </el-form-item>

        <el-form-item label="合计金额（万元）" prop="totalAmount">
          <el-input
            v-model="formData.totalAmount"
            placeholder="合计金额（万元）"
          />
        </el-form-item>

        <el-form-item label="现货周转天数" prop="spotTurnoverDays">
          <el-input
            v-model="formData.spotTurnoverDays"
            placeholder="现货周转天数"
          />
        </el-form-item>

        <el-form-item label="含在途周转天数" prop="withInTransitTurnoverDays">
          <el-input
            v-model="formData.withInTransitTurnoverDays"
            placeholder="含在途周转天数"
          />
        </el-form-item>

        <el-form-item label="本月NR目标（万元）" prop="nrTarget">
          <el-input
            v-model="formData.nrTarget"
            placeholder="本月NR目标（万元）"
          />
        </el-form-item>

        <el-form-item label="已下单金额（万元）" prop="orderedAmount">
          <el-input
            v-model="formData.orderedAmount"
            placeholder="已下单金额（万元）"
          />
        </el-form-item>

        <el-form-item label="达成率（%）" prop="achievementRate">
          <el-input
            v-model="formData.achievementRate"
            placeholder="达成率（%）"
          />
        </el-form-item>

        <el-form-item label="PV现货率（%）" prop="pvSpotRate">
          <el-input
            v-model="formData.pvSpotRate"
            placeholder="PV现货率（%）"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SupplyChainReport",
  inheritAttrs: false,
});

import SupplyChainReportAPI, { SupplyChainReportPageVO, SupplyChainReportForm, SupplyChainReportPageQuery } from "@/api/system/supply-chain-report";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<SupplyChainReportPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 供应链日报表格数据
const pageData = ref<SupplyChainReportPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 供应链日报表单数据
const formData = reactive<SupplyChainReportForm>({});

// 供应链日报表单校验规则
const rules = reactive({
  storeName: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
  reportDate: [{ required: true, message: "请输入报告日期", trigger: "blur" }],
  spotQuantity: [{ required: true, message: "请输入现货数量（箱）", trigger: "blur" }],
  inTransitQuantity: [{ required: true, message: "请输入在途数量（箱）", trigger: "blur" }],
  totalQuantity: [{ required: true, message: "请输入合计数量（箱）", trigger: "blur" }],
  spotAmount: [{ required: true, message: "请输入现货金额（万元）", trigger: "blur" }],
  inTransitAmount: [{ required: true, message: "请输入在途金额（万元）", trigger: "blur" }],
  totalAmount: [{ required: true, message: "请输入合计金额（万元）", trigger: "blur" }],
  spotTurnoverDays: [{ required: true, message: "请输入现货周转天数", trigger: "blur" }],
  withInTransitTurnoverDays: [{ required: true, message: "请输入含在途周转天数", trigger: "blur" }],
  nrTarget: [{ required: true, message: "请输入本月NR目标（万元）", trigger: "blur" }],
  orderedAmount: [{ required: true, message: "请输入已下单金额（万元）", trigger: "blur" }],
  achievementRate: [{ required: true, message: "请输入达成率（%）", trigger: "blur" }],
  pvSpotRate: [{ required: true, message: "请输入PV现货率（%）", trigger: "blur" }],
});

/** 查询供应链日报 */
function handleQuery() {
  loading.value = true;
  SupplyChainReportAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置供应链日报查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开供应链日报弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改供应链日报";
    SupplyChainReportAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增供应链日报";
  }
}

/** 提交供应链日报表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SupplyChainReportAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        SupplyChainReportAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭供应链日报弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除供应链日报 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SupplyChainReportAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
